{% extends 'base.html' %}
{% load staticfiles %}
{% block title %}Course List{% endblock %}

{% block content %}
<div class="container">
    <div class="text-right">
        <a href="{% url 'course:course_create' %}">
            <button:button class="btn btn-primary">发布课程</button:button>
        </a>
    </div>
    <table class="table table-hover">
        <tr>
            <td>序号</td>
            <td>标题</td>
            <td>讲师</td>
            <td>日期</td>
            <td>操作</td>
        </tr>
        {% for course in courses %}
            <tr id={{ forloop.counter }}>
                <td>{{ forloop.counter }}</td>
                <td>{{ course.title }}</td>
                <td>{{ course.user.username }}</td>
                <td>{{ course.created }}</td>
                <td>
                    <a href="{% url 'course:course_delete' course.id %}" class="delete">
                        <span class="glyphicon glyphicon-trash" style="margin-left:20px;"></span>
                    </a>
                </td>
            </tr>
        {% endfor %}
    </table>
</div>
<script src="{% static 'js/jquery-3.4.1.js' %}"></script>
<script>
    function getCookie(name) {
        var cookieValue = null;
        if (document.cookie && document.cookie != '') {
            var cookies = document.cookie.split(';');
            for (var i = 0; i < cookies.length; i++) {
                var cookie = jQuery.trim(cookies[i]);
                if (cookie.substring(0, name.length + 1) == (name + '=')) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookieValue
    }
    $(document).ready(function() {
        var csrftoken = getCookie('csrftoken');
        function csrfSafeMethod(method) {
            return (/^(GET|HEAD|OPTOINS|TRACE)$/.test(method));
        }
        $.ajaxSetup({
            crossDomain: false, // obviates need for sameOrigin test
            beforeSend: function(xhr, settings) {
                if (!csrfSafeMethod(settings.type)) {
                    xhr.setRequestHeader('X-CSRFTOKEN', csrftoken);
                }
            }
        });
        var onDelete = function(){
            if (!confirm('delete it? ')) return false;
            $.post(this.href, function(data) {
                if (data.result == 'ok') {
                    window.location.reload()
                } else {
                    alert('sth wrong');
                }
            }).fail(function(){
                alert('error');
            });
            return false;
        }
        $('.delete').click(onDelete)
    })
</script>
{% endblock %}